﻿using System;
using System.Configuration;
using System.Dynamic;
using System.Web.Security;
using Facebook.Web;
using Facebook;
using System.Collections.Generic;
using FacebookPoster;
using System.Web.UI.WebControls;
using FPModel;
using log4net;


namespace CS_AspNetWebForms_JsSdk.Facebook
{
    public partial class Default : System.Web.UI.Page
    {
        private static readonly log4net.ILog _logger = LogManager.GetLogger(typeof(Default));
        protected void Page_Load(object sender, EventArgs e)
        {
            var extendedPermissions = ConfigurationManager.AppSettings["extendedPermissions"].Split(',');

            if (!FacebookWebContext.Current.IsAuthorized(extendedPermissions))
            {
                // this sample actually does not make use of FormsAuthentication,
                // besides redirecting to the proper login url defined in web.config
                // this will also automatically add ReturnUrl.
                FormsAuthentication.RedirectToLoginPage();
            }
            else
            {
                // checking IsPostBack may reduce the number of requessts to Facebook server.
                if (!IsPostBack)
                {
                    try
                    {
                        if (_logger.IsDebugEnabled)
                        {
                            _logger.Debug("Kullanıcıdan veri alınıyor");
                        }

                        var fb = new FacebookWebClient();
                        dynamic me = fb.Get("me");

                        imgProfilePic.ImageUrl = string.Format("https://graph.facebook.com/{0}/picture", me.id);

                        //fb.AccessToken = string.Format("https://graph.facebook.com/{0}/accounts?access_token={1}", me.id, fb.AccessToken);

                        //fb.AccessToken = "AAAEODr05H9sBABfrrWfZB1uye4uqTNQENInKi1O0DpTSErXJZA1r50MuZAH807kI3jHHhoLH8lkQjABhwfV5h0a2SGurcCcG7MItN1g0QZDZD";

                        string accessToken = fb.AccessToken;
                        lblName.Text = me.name;
                        lblFirstName.Text = me.first_name;
                        lblLastName.Text = me.last_name;
                        string userId = me.id;

                        using (FBPosterEntities context = new FBPosterEntities())
                        {
                            FBUser existingfbUser = FacebookPoster.User.GetByUserToken(fb.AccessToken);

                            if (existingfbUser == null)
                            {
                                FBUser fbUser = new FBUser();
                                fbUser.FirstName = me.first_name;
                                fbUser.LastName = me.last_name;
                                fbUser.UserToken = fb.AccessToken;
                                fbUser.UserID = me.id;
                                
                                context.FBUsers.AddObject(fbUser);
                                context.SaveChanges();

                                string sPages = "SELECT page_id,page_url,name,pic_square FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid =  " + me.id + ") ";
                                string sPagesResult = string.Empty;
                                dynamic pages = fb.Query(sPages);
                                foreach (dynamic page in pages)
                                {
                                    string pageName = String.Format("{0}", page.name);
                                    string pageId = String.Format("{0}", page.page_id);
                                    string page_url = String.Format("{0}", page.page_url);
                                    string pic_square = String.Format("{0}", page.pic_square);

                                    FBPage fbPages = new FBPage();
                                    fbPages.UserID = fbUser.ID;
                                    fbPages.PageName = pageName;
                                    fbPages.PageNo = pageId;
                                    fbPages.PageLink = page_url;
                                    fbPages.PageToken = GetPageAccessToken(fb.AccessToken, pageId);
                                    
                                    context.FBPages.AddObject(fbPages);
                                    context.SaveChanges();
                                }
                            }

                            string sPages2 = "SELECT page_id,page_url,name,pic_square FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid =  " + me.id + ") ";
                            string sPagesResult2 = string.Empty;
                            dynamic pages2 = fb.Query(sPages2);
                            foreach (dynamic page in pages2)
                            {
                                string pageName = String.Format("{0}", page.name);
                                string pageId = String.Format("{0}", page.page_id);
                                string page_url = String.Format("{0}", page.page_url);
                                string pic_square = String.Format("{0}", page.pic_square);

                                lbPages.Items.Add(new System.Web.UI.WebControls.ListItem(pageName, pageId));
                            }

                            //dynamic parameters = new ExpandoObject();
                            //parameters.q = "SELECT name, uid FROM user WHERE uid = me()";
                            //dynamic result = fb.Get("fql", parameters);
                            //lblPages.Text = result;

                            //get page access token
                            //https://graph.facebook.com/$USERID/accounts?access_token=$USER_ACCESS_TOKEN
                            //https://graph.facebook.com/me/accounts?access_token=[user-access_token]
                        }

                        FBSession.UserID = FacebookPoster.User.GetByID(userId).ID;
                    }
                    catch (Exception ex)
                    {
                        string error = ex.Message;
                        //error handling code
                        throw;
                    }
                }
            }
        }

        public static string GetPageAccessToken(string accessToken, string pageId)
        {
            try
            {
                var fb = new FacebookClient(accessToken);

                var parameters = new Dictionary<string, object>();

                // Note that the access_token field is a non-default field and
                // must be requested explicitly via the fields URL parameter.
                // In addition, you must use a user access_token with the 
                // manage_pages permission to make this request, 
                // where the user is an administrator of the Page. 
                parameters["fields"] = "access_token";
                var result = (IDictionary<string, object>)fb.Get(pageId, parameters);

                var pageAccessToken = (string)result["access_token"];

                return pageAccessToken;
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }

        protected void btnPostToWall_Click(object sender, EventArgs e)
        {
            var fb = new FacebookWebClient();

            dynamic parameters = new ExpandoObject();
            parameters.message = txtMessage.Text;

            try
            {
                int[] pageIds = lbPages.GetSelectedIndices();

                List<String> selectedPageIds = new List<string>();
                string value = string.Empty;

                for (int i = 0; i < pageIds.Length; i++)
                    selectedPageIds.Add(lbPages.Items[pageIds[i]].Value);

                string pageId = lbPages.SelectedValue.ToString();

                using (FBPosterEntities context = new FBPosterEntities())
                {
                    foreach (var item in selectedPageIds)
                    {
                        string accessTokenPage = GetPageAccessToken(fb.AccessToken, item.ToString());

                        var fbPages = new FacebookWebClient(accessTokenPage);

                        var args = new Dictionary<string, object>();
                        args["message"] = txtMessage.Text;
                        args["description"] = txtDescription.Text;
                        args["name"] = txtName.Text;
                        args["link"] = txtCaption.Text;
                        string postMessage = string.Format("/{0}/feed", item.ToString());
                        fbPages.Post(postMessage, args);

                        DateTime postDate = DateTime.ParseExact(datepicker.Text, "MM/dd/yyyy HH:mm",
                                       System.Globalization.CultureInfo.InvariantCulture);

                        DateTime postedDate = DateTime.ParseExact(datepicker.Text, "MM/dd/yyyy HH:mm",
                                       System.Globalization.CultureInfo.InvariantCulture);

                        FBPagePost fbPagePost = new FBPagePost();
                        fbPagePost.UserID = FBSession.UserID;
                        fbPagePost.PageID = Pages.GetByPageToken(accessTokenPage).ID;
                        fbPagePost.Description = txtDescription.Text;
                        fbPagePost.Link = txtCaption.Text;
                        fbPagePost.Message = txtMessage.Text;
                        fbPagePost.Name = txtName.Text;
                        fbPagePost.PageNo = FBSession.PageID;
                        fbPagePost.PostDate = postDate;
                        fbPagePost.PostedDate = postedDate;
                        fbPagePost.PostHour = timepicker.Text;
                        fbPagePost.IsPosted = true;

                        context.FBPagePosts.AddObject(fbPagePost);
                        context.SaveChanges();
                    }
                }

                lblPostMessageResult.Text = "Message posted successfully";
                txtMessage.Text = string.Empty;
            }
            catch (FacebookApiException ex)
            {
                lblPostMessageResult.Text = ex.Message;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var fb = new FacebookWebClient();

            dynamic parameters = new ExpandoObject();
            parameters.message = txtMessage.Text;

            try
            {
                int[] pageIds = lbPages.GetSelectedIndices();

                List<String> selectedPageIds = new List<string>();
                string value = string.Empty;

                for (int i = 0; i < pageIds.Length; i++)
                    selectedPageIds.Add(lbPages.Items[pageIds[i]].Value);

                string pageId = lbPages.SelectedValue.ToString();

                using (FBPosterEntities context = new FBPosterEntities())
                {
                    foreach (var item in selectedPageIds)
                    {
                        string accessTokenPage = GetPageAccessToken(fb.AccessToken, item.ToString());

                        DateTime postDate = DateTime.ParseExact(datepicker.Text, "MM/dd/yyyy HH:mm",
                                       System.Globalization.CultureInfo.InvariantCulture);

                        DateTime postedDate = DateTime.ParseExact(datepicker.Text, "MM/dd/yyyy HH:mm",
                                       System.Globalization.CultureInfo.InvariantCulture);

                        FBPagePost fbPagePost = new FBPagePost();
                        fbPagePost.UserID = FBSession.UserID;
                        fbPagePost.PageID = Pages.GetByPageToken(accessTokenPage).ID;
                        fbPagePost.Description = txtDescription.Text;
                        fbPagePost.Link = txtCaption.Text;
                        fbPagePost.Message = txtMessage.Text;
                        fbPagePost.Name = txtName.Text;
                        fbPagePost.PageNo = FBSession.PageID;
                        fbPagePost.PostDate = postDate;
                        fbPagePost.PostedDate = postedDate;
                        fbPagePost.PostHour = timepicker.Text;
                        fbPagePost.IsPosted = false;

                        context.FBPagePosts.AddObject(fbPagePost);
                        context.SaveChanges();
                    }
                }

                lblPostMessageResult.Text = "Message posted successfully";
                txtMessage.Text = string.Empty;

            }
            catch (FacebookApiException ex)
            {
                lblPostMessageResult.Text = ex.Message;
            }
        }
    }
}